// 骨质疏松健康管理平台 - API 服务器
// 用于 Web 端调用 App 数据

const express = require('express');
const cors = require('cors');
try { require('dotenv').config(); } catch (_) { /* 可选 */ }
const app = express();
const PORT = 3000;

// 中间件
app.use(cors());
app.use(express.json());

// 模拟数据
const mockData = {
  // 用户信息
  user: {
    id: 'user_001',
    name: '李华',
    age: 65,
    gender: '女',
    phone: '13800138000',
    email: 'lihua@example.com'
  },

  // 问卷历史记录
  questionnaireHistory: [
    {
      date: '2025-10-28',
      score: 12,
      riskLevel: '中',
      answers: [1, 1, 0, 1, 0, 1, 1, 1, 0, 0]
    },
    {
      date: '2025-10-21',
      score: 14,
      riskLevel: '高',
      answers: [1, 1, 1, 1, 0, 1, 1, 1, 0, 1]
    },
    {
      date: '2025-10-14',
      score: 10,
      riskLevel: '低',
      answers: [1, 0, 0, 1, 0, 1, 0, 1, 0, 0]
    }
  ],

  // 骨密度检测历史
  boneDensityHistory: [
    {
      date: '2025-10-27',
      type: 'DXA',
      tScore: -1.8,
      zScore: -0.5,
      diagnosis: '骨量减少'
    },
    {
      date: '2025-10-20',
      type: 'Ultrasound',
      tScore: -2.1,
      zScore: -1.2,
      diagnosis: '骨质疏松'
    },
    {
      date: '2025-10-10',
      type: 'DXA',
      tScore: -1.5,
      zScore: -0.3,
      diagnosis: '骨量减少'
    }
  ],

  // 运动记录
  exerciseRecords: [
    {
      date: '2025-10-30',
      duration: 45,
      exercises: ['快走', '太极拳'],
      calories: 280
    },
    {
      date: '2025-10-29',
      duration: 30,
      exercises: ['游泳'],
      calories: 200
    },
    {
      date: '2025-10-28',
      duration: 60,
      exercises: ['快走', '柔软体操'],
      calories: 350
    },
    {
      date: '2025-10-27',
      duration: 40,
      exercises: ['太极拳'],
      calories: 150
    },
    {
      date: '2025-10-26',
      duration: 50,
      exercises: ['快走', '乒乓球'],
      calories: 320
    }
  ],

  // 用药提醒
  medicationReminders: [
    {
      id: 'med_001',
      name: '钙片',
      type: 'medication',
      time: '08:00',
      frequency: 'daily',
      dosage: '2片',
      notes: '饭后30分钟服用',
      completedDates: ['2025-10-30', '2025-10-29', '2025-10-28']
    },
    {
      id: 'med_002',
      name: '维生素D',
      type: 'medication',
      time: '12:00',
      frequency: 'daily',
      dosage: '1粒',
      notes: '随餐服用',
      completedDates: ['2025-10-30', '2025-10-29']
    },
    {
      id: 'med_003',
      name: '牛奶',
      type: 'nutrition',
      time: '20:00',
      frequency: 'daily',
      dosage: '200ml',
      notes: '温牛奶',
      completedDates: ['2025-10-30']
    }
  ],

  // 统计数据
  statistics: {
    thisWeekExercise: {
      totalMinutes: 225,
      sessions: 5,
      calories: 1300
    },
    thisMonthExercise: {
      totalMinutes: 850,
      sessions: 18,
      calories: 5200
    },
    medicationAdherence: {
      completed: 8,
      missed: 2,
      adherenceRate: 80
    },
    boneHealthStatus: {
      latestTScore: -1.8,
      latestDiagnosis: '骨量减少',
      trend: 'stable'
    }
  }
};

// API 路由

// LLM 预测（演示：支持 OpenAI 接口兼容，也提供本地 Mock 回退）
app.post('/api/llm/predict', async (req, res) => {
  try {
    const { prompt, system, model } = req.body || {};
    const BASE = process.env.LLM_BASE_URL || 'https://api.openai.com/v1'; // 缺省走 OpenAI 兼容
    const KEY = process.env.LLM_API_KEY;   // 请通过环境变量或 .env 配置
    const mdl = model || process.env.LLM_MODEL || 'gpt-4o-mini';

    // 若未配置 Key，则返回 Mock 预测，保证演示可用
    if (!BASE || !KEY) {
      return res.json({
        success: true,
        data: { model: 'mock', output: `【演示结果】你输入了：${prompt?.slice(0,60) || ''}...` }
      });
    }

    const resp = await fetch(`${BASE}/chat/completions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${KEY}`
      },
      body: JSON.stringify({
        model: mdl,
        messages: [
          ...(system ? [{ role: 'system', content: system }] : []),
          { role: 'user', content: prompt || '' }
        ]
      })
    });
    if (!resp.ok) throw new Error(`${resp.status} ${resp.statusText}`);
    const json = await resp.json();
    const text = json.choices?.[0]?.message?.content || '';
    res.json({ success: true, data: { model: mdl, output: text } });
  } catch (e) {
    res.status(500).json({ success: false, message: String(e) });
  }
});

// 1. 获取用户信息
app.get('/api/user', (req, res) => {
  res.json({
    success: true,
    data: mockData.user
  });
});

// 2. 获取问卷历史
app.get('/api/questionnaire-history', (req, res) => {
  res.json({
    success: true,
    data: mockData.questionnaireHistory,
    count: mockData.questionnaireHistory.length
  });
});

// 3. 获取骨密度检测历史
app.get('/api/bone-density-history', (req, res) => {
  res.json({
    success: true,
    data: mockData.boneDensityHistory,
    count: mockData.boneDensityHistory.length
  });
});

// 4. 获取运动记录
app.get('/api/exercise-records', (req, res) => {
  res.json({
    success: true,
    data: mockData.exerciseRecords,
    count: mockData.exerciseRecords.length
  });
});

// 5. 获取用药提醒
app.get('/api/medication-reminders', (req, res) => {
  res.json({
    success: true,
    data: mockData.medicationReminders,
    count: mockData.medicationReminders.length
  });
});

// 6. 获取统计数据
app.get('/api/statistics', (req, res) => {
  res.json({
    success: true,
    data: mockData.statistics
  });
});

// 7. 获取所有数据（打包下载）
app.get('/api/all-data', (req, res) => {
  res.json({
    success: true,
    data: mockData,
    timestamp: new Date().toISOString()
  });
});

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({
    success: true,
    message: '骨质疏松健康管理平台 API 服务正常运行',
    timestamp: new Date().toISOString()
  });
});

// 404 处理
app.use((req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在'
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`
╔════════════════════════════════════════╗
║  骨质疏松健康管理平台 API 服务器启动  ║
╚════════════════════════════════════════╝
  
  服务地址: http://localhost:${PORT}
  
  可用接口:
  - GET  /api/health                    (健康检查)
  - GET  /api/user                      (用户信息)
  - GET  /api/questionnaire-history     (问卷历史)
  - GET  /api/bone-density-history      (骨密度检测)
  - GET  /api/exercise-records          (运动记录)
  - GET  /api/medication-reminders      (用药提醒)
  - GET  /api/statistics                (统计数据)
  - GET  /api/all-data                  (所有数据)
  
  使用示例:
  curl http://localhost:${PORT}/api/user
  curl http://localhost:${PORT}/api/exercise-records
  `)
});
